package _4响应体;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/TestServlet5")
public class TestServlet5 extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("image/jpeg;");

		// 1. 得到输出字节流
		BufferedOutputStream bos = new BufferedOutputStream(resp.getOutputStream());
		// 2. 得到文件的输出流
		ServletContext sc = getServletContext();
		int id = (int) (Math.random() * 3) + 1;
		String filePath = sc.getRealPath("/WEB-INF/" + id + ".jpg");
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));

		// 3. 从文件流读取，写入到输出流
		byte[] buf = new byte[1024];
		int len = 0;
		while ((len = bis.read(buf)) != -1) {
			bos.write(buf, 0, len);
		}

		// 4. 关闭流
//		bos.close();
		bis.close();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}